<template>
    <div>
      <h3>Product Manager</h3>
      <form class="form-inline">
        <div class="form-group">
          <input type="text" class="form-control"  placeholder="name" v-model="p.name">
        </div>
        <div class="form-group">
          <input type="number" class="form-control"  v-model="p.price">
        </div>

        <div class="form-group">
          <input type="number" class="form-control"  v-model="p.quantity">
        </div>
        <button @click.prevent="addProduct" class="btn btn-default" type="submit">add</button>

      </form>





      <table class="table">
        <tr v-for="p of products">
          <td>{{p.name}}</td>
          <td>{{p.price}}</td>
          <td><input type="number" v-model="p.quantity"></td>
          <td><button class="btn btn-info" @click="deleteProduct(p)">delete</button></td>
          <td><button class="btn btn-primary" @click="updateProduct(p)">update</button></td>
          <td><template v-if="p.quantity==0">缺货</template></td>
        </tr>
      </table>

    </div>
</template>

<script>


    export default {
        name: "product-manager",
        created(){
          fetch(this.url,{method:"GET"})
             .then(resp=>resp.json())
            .then(data=>this.products=data)

        },
        data(){
          return{
            p:{name:"john",price:100,quantity:12},
            url:"http://localhost:3000/products",
            products:[]
          }
        },
      methods:{
          deleteProduct(p){
            fetch(this.url+"/"+p.id,{method:"DELETE"})
              .then(resp=>{
                let index=this.products.indexOf(p);
                this.products.splice(index,1)
              })
          },
          addProduct(){
            fetch(this.url,{method:"POST",body:JSON.stringify(this.p),headers:{"Content-Type":"application/json"}})
              .then(resp=>resp.json())
              .then(p=>this.products.push(p))
          },
          updateProduct(p){
            fetch(this.url+"/"+p.id,{method:"PUT",body:JSON.stringify(p),headers:{"Content-Type":"application/json"}})
              .then(resp=>{});
          }
      }
    }
</script>

<style scoped>
  h3{
    color:red;
  }
  .table tr{
    line-height: 50px;
  }
  .table td{
    line-height: 35px;
  }
</style>













